/**
 * Author:
 * Date:
 * Description: ""
 */
require("../common/common.scss");
require("./index.scss");

var dialog = require('COMMON/modules/dialog-simple');

var loading = require('COMMON/js/util.loading.pc.js');

var PaginationX = require("COMMON/modules/pagination-x/v1.0");

var Toast = require('COMMON/modules/Toast');
var toast = new Toast;

var ParseTemplate = ZFT.Util.ParseTemplate;
var Template = {
    tr: ParseTemplate(require("./tpl/tr.xtpl")),
    billDetail: ParseTemplate(require("./tpl/detail.xtpl")),
   // advicenote: ParseTemplate(require("./tpl/advicenote.xtpl"))
};

var Main = ZFT.Util.Class({
    PAGE_SIZE: 15,

    selectedContract: [],

    FEE_TYPE: [
        '房租',
        '物业',
        '水',
        '电',
        '公摊水',
        '公摊电',
        '税费',
        '其他费用',
        /*'优惠金额'*/
    ],

    dom: {

        filter: '#filter',
        beginDate: '#beginDate',
        endDate: '#endDate',
        state: '#state',
        btnQuery: '#btnQuery',

        checkAll: '#checkAll',

        tbBill: '#tbBill',

        btnPay: '#btnPay',
        pagination: $(".paginationWrap"),
        billDetail: '#billDetail'
    },

    xhrGetBillList: null,

    init: function () {
        var _this = this;

        var dom = _this.dom;

        this.params = {
            begin_month: '',
            end_month: '',
            status: '0',
            page: 1,
            page_size: this.PAGE_SIZE
        };

        this.ajaxGetBillList(this.params);

        $('#beginDate').datepicker({
            format: "yyyymm",
            startView: 1,
            minViewMode: 1,
            maxViewMode: 2,
            language: "zh-CN",
            autoclose: true
        });

        $('#endDate').datepicker({
            format: "yyyymm",
            startView: 1,
            minViewMode: 1,
            maxViewMode: 2,
            language: "zh-CN",
            autoclose: true
        });

        // $( this.dom.checkAll ).on('click', function(){

        //     if( $(this).prop('checked') ) {
        //         _this.selectContract();
        //     } else {
        //         _this.unSelectContract();
        //     }

        // });

        $(this.dom.tbBill).on('click', '.btn-getdetail', function (e) {

            var target = $(e.target),
                id = target.attr('data-id'),
                status = target.attr('data-status'),
                begin_cycle = target.attr('data-begin'),
                end_cycle = target.attr('data-end');

            _this.ajaxGetBillDetail(id, status, begin_cycle, end_cycle);

        });/*.on('click','.btn-note',function(e){

            _this.ajaxGetNote();
        });*/
        // .on('click', 'tbody :checkbox', function(){

        //     if( $(this).prop('checked') ) {
        //         _this.selectContract( $(this).attr('data-id') );
        //     } else {
        //         _this.unSelectContract( $(this).attr('data-id') );
        //     }

        // });
        
        $(this.dom.btnQuery).on('click', function () {
            var beginDate = $.trim($(_this.dom.beginDate).val()),
                endDate = $.trim($(_this.dom.endDate).val());
            var page_size = $(".paginationWrap").attr("data-size");
            if (beginDate > endDate) {
                ZFT.Util.STip('fail', '起始时间不能大于结束时间');
                return false;
            }

            if ($(_this.dom.state).val() == 1) {
                $(_this.dom.btnPay).hide();
            } else {
                $(_this.dom.btnPay).show();
            }


            _this.params = {
                begin_month: beginDate,
                end_month: endDate,
                status: $(_this.dom.state).val(),
                page: 1,
                page_size: page_size ? page_size : _this.PAGE_SIZE
            };

            //  console.log( _this.params )
            // _this.selectedContract = [];
            _this.ajaxGetBillList(_this.params);
        });

        // $( this.dom.btnPay ).on('click', function(){
        //     if( _this.selectedContract.length ) {
        //         location.href = 'pay?ids=' + _this.selectedContract.join()
        //     } else {
        //         ZFT.Util.STip('fail','至少选择一个账单');
        //     }
        // });
        $(this.dom.billDetail).on("click", ".close", function (e) {
            var tarBtn = $(e.currentTarget);
            tarBtn.parents(".m-modal_bg").fadeOut(200);
        })
    },

    ajaxGetBillList: function (params) {
        var _this = this;

        this.xhrGetBillList = this.ajaxRenderData({
            container: this.dom.tbBill + ' tbody',
            url: '/r/BillManager_leaseBill',
            params: params,
            loading: {
                id: 'billLoading',
                text: '正在努力加载您的账单...',
                className: 'tb-loading',
                colspan: 8,
                tag: 'td',
                hidePage:function(){
                    _this.dom.pagination.hide();
                }
            },
            success: function (res) {
                _this.renderBillList(res.data.list);

                if (_this.pagination) {

                    _this.pagination.render({ current: res.data.current_page, total: res.data.total });

                } else {

                    _this.pagination = new PaginationX({
                        container: $(".paginationWrap"),
                        count: 7,
                        showTotal: true,
                        jump: true,
                        filter: true
                    });

                    _this.pagination.on("page.switch", function (toPage, current, total) {
                        var page_size = $(".paginationWrap").attr("data-size");
                        $(_this.dom.checkAll).prop('checked', false);

                        _this.params.page = toPage;
                        _this.params.page_size = page_size ? page_size : 15;
                        _this.ajaxGetBillList(_this.params);

                    });

                    _this.pagination.render({ current: res.data.current_page, total: res.data.total });

                }
            },
            error: function (res) {
                $(_this.dom.tbBill + ' tbody').html('<tr><td colspan="8" align="center" class="tb-nodata">' + res.msg + '</td></tr>');
            }
        })
    },
    ajaxRenderData: function (opts) {
        return ZFT.Util.Ajax(opts.url, {
            type: 'POST',
            params: opts.params,
            loading: function () {
                var loadingOpts = {};

                loadingOpts.id = opts.loading.id;
                loadingOpts.text = opts.loading.text || '';
                loadingOpts.className = opts.loading.className;
                loadingOpts.tag = opts.loading.tag || '';
                if (opts.loading.tag == 'td') {
                    loadingOpts.colspan = opts.loading.colspan ? opts.loading.colspan : '';
                }

                var html = loading(opts.loading.text, loadingOpts);
                $(opts.container).html(html);
                if(opts.loading.hidePage) opts.loading.hidePage();
            },
            success: function (res) {
                $('#' + opts.loading.id).remove();


                if (res.code == 200 || res.code == 'success') {
                    opts.success && opts.success(res);
                } else {

                    opts.error && opts.error(res);
                }
            },
            serverError: function (xhr, txt) {

            }
        })
    },

    renderBillList: function (data) {
        var html = Template.tr({ data: data });
        $(this.dom.tbBill + ' tbody').html(html);
    },

    ajaxGetBillDetail: function (id, status, begin_cycle, end_cycle) {
        var _this = this;

        this.xhrGetBillDetail = this.ajaxRenderData({
            container: this.billDetail,
            url: '/r/BillManager_leaseBillDetail',
            params: {
                id: id,
                begin_cycle: begin_cycle,
                end_cycle: end_cycle,
                status: status
            },
            loading: {
                id: 'billDetailLoading',
                text: '正在努力加载您的账单明细...',
                className: 'tb-loading',
                colspan: 2,
                tag: 'td'
            },
            success: function (res) {
                _this.renderBillDetail(res.data);
            },
            error: function (res) {
                $(_this.dom.tbBillDetail + ' tbody').html('<tr><td colspan="10" align="center" class="tb-nodata">' + res.msg + '</td></tr>');
            }
        })
    },
    renderBillDetail: function (data) {
        var _this=this;
        var list=data.list;
        for (var i = 0, dataLen = list.length; i < dataLen; i++) {
            list[i].type = _this.FEE_TYPE[list[i].type_money - 1]
        }

        var begin_cycle = list[0].begin_cycle,
            end_cycle = list[0].end_cycle;

        var html = Template.billDetail({ data: data, begin_cycle: begin_cycle, end_cycle: end_cycle });
        $(_this.dom.billDetail).html(html);
    },
    selectContract: function (id) {
        var allCheckbox = $(this.dom.tbBill + ' tbody').find(':checkbox');

        if (id === undefined) {
            allCheckbox.prop('checked', true);

            var checkedArr = allCheckbox.map(function () {
                return $(this).attr('data-id');
            });

            this.selectedContract = this.concatArr(this.selectedContract, checkedArr);
        } else {
            if (this.selectedContract.indexOf(id) == -1) {
                this.selectedContract.push(id);

                if (allCheckbox.filter(':checked').length == allCheckbox.length) {
                    $(this.dom.checkAll).prop('checked', true);
                }
            }
        }
    },
    unSelectContract: function (id) {
        var _this = this;

        if (id === undefined) {

            var allCheckbox = $(this.dom.tbBill + ' tbody').find(':checkbox');

            allCheckbox.prop('checked', false);

            allCheckbox.each(function (i) {
                if (_this.selectedContract.indexOf($(this).attr('data-id')) != -1) {
                    _this.selectedContract.splice(_this.selectedContract.indexOf($(this).attr('data-id')), 1);
                }
            });

        } else {

            if (this.selectedContract.indexOf(id) != -1) {
                this.selectedContract.splice(this.selectedContract.indexOf(id), 1);
            }

            $(_this.dom.checkAll).prop('checked', false);
        }
    },
    concatArr: function (arr1, arr2) {
        arr1.push.apply(arr1, arr2);

        var n = {}, r = []; //n为hash表，r为临时数组
        for (var i = 0; i < arr1.length; i++) //遍历当前数组
        {
            if (!n[arr1[i]]) //如果hash表中没有当前项
            {
                n[arr1[i]] = true; //存入hash表
                r.push(arr1[i]); //把当前数组的当前项push到临时数组里面
            }
        }

        return r;
    },
    //获取交费通知单
    ajaxGetNote:function(){
        var _this=this;
        var html=Template.advicenote();
        $(_this.dom.billDetail).html(html);
        
    }

});

$(function () {
    new Main();
})